using Microsoft.AspNetCore.Mvc;
using web_api.Domain;

namespace web_api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BlogsController(AdminDbContext db) : ControllerBase
{
    private readonly AdminDbContext _db = db;

    [HttpGet]
    public IActionResult Get()
    {
        var List = _db.Blogs.ToList();
        return Ok(new
        {
            code = 200,
            msg = "获取博客列表成功",
            data = List
        });
    }

    [HttpPost]
    public IActionResult Post(Blogs blogs)
    {
        _db.Blogs.Add(blogs);
        _db.SaveChanges();
        return Ok(new
        {
            code = 200,
            msg = "添加博客成功",
            data = blogs
        });
    }

    [HttpPut("{id}")]
    public IActionResult Put(int id, Blogs blogs)
    {
        var blog = _db.Blogs.FirstOrDefault(b => b.Id == id);
        if (blog == null)
        {
            return NotFound(new
            {
                code = 404,
                msg = "博客未找到"
            });
        }
        blog.Title = blogs.Title;
        blog.Author = blogs.Author;
        blog.Content = blogs.Content;
        _db.Blogs.Update(blog);
        _db.SaveChanges();
        return Ok(new
        {
            code = 200,
            msg = "更新博客成功",
            data = blog
        });
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var blog = _db.Blogs.FirstOrDefault(b => b.Id == id);
        if (blog == null)
        {
            return NotFound(new
            {
                code = 404,
                msg = "博客未找到"
            });
        }
        _db.Blogs.Remove(blog);
        _db.SaveChanges();
        return Ok(new
        {
            code = 200,
            msg = "删除博客成功"
        });
    }
}